package com.yoso.shop.infrastructure.utils;

import com.alibaba.fastjson.JSON;
import com.yoso.api.info.log.OrderLogInfo;
import com.yoso.api.info.log.StockLogInfo;
import com.yoso.shop.infrastructure.config.RabbitmqConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author shizejin
 * @date 2022/1/28
 * @description:
 */
@Component
public class RabbitMqUtils {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RabbitmqConfig rabbitmqConfig;

    /**
     * 更新订单信息
     */
    public void flushOrderInfo(OrderLogInfo orderLogInfo) {
        rabbitTemplate.setExchange(rabbitmqConfig.getOrderLogExchange());
        Message message = new Message(JSON.toJSONString(orderLogInfo).getBytes(StandardCharsets.UTF_8));
        rabbitTemplate.convertAndSend("", message);
    }

    /**
     * 更新库存信息
     */
    public void flushStockInfo(StockLogInfo stockLogInfo) {
        rabbitTemplate.setExchange(rabbitmqConfig.getStockLogExchange());
        Message message = new Message(JSON.toJSONString(stockLogInfo).getBytes(StandardCharsets.UTF_8));
        rabbitTemplate.convertAndSend("", message);
    }

    public void sendDelayOrderConfirmMsg(OrderLogInfo orderLogInfo) {
        rabbitTemplate.setExchange(rabbitmqConfig.getDelayOrderConfirmExchange());
        Message message = new Message(JSON.toJSONString(orderLogInfo).getBytes(StandardCharsets.UTF_8));
        rabbitTemplate.convertAndSend("order.confirm", message,(processor)->{
            processor.getMessageProperties().setDelay(30*1000);
            return processor;
        });
    }
}
